package mysql

import (
	"bluebell/models"
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	"go.uber.org/zap"
)

const secret = "zyl"

// 这个错误变量感觉不大行
var (
	ErrorUserExist    = errors.New("用户已经存在")
	ErrorUserNotExist = errors.New("用户未注册")
	ErrorPwd          = errors.New("密码输入错误！")
)

// 负责数据查询和存储，并不关心业务逻辑

// 查询是否登陆成功，并返回登录成功的
func CheckUserExistAndPasswordTrue(username string, password string) (err error, user *models.User) {
	user = new(models.User) // 指针类型需要提前分配内存
	sqlStr := "select user_id, username, password from user where username = ?"
	//var u models.ParamLogIN
	err = db.Get(user, sqlStr, username)
	//fmt.Println(u)
	if err == sql.ErrNoRows {
		return ErrorUserNotExist, user
	}
	if err != nil {
		return err, user

	}
	// 检查密码是否正确
	salt := encryptPassword([]byte(password))
	if salt != user.Password {
		return ErrorPwd, user
	}

	return nil, user

}

// 从数据库查询此用户是否已经存在
func CheckUserExist(username string) (bool, error) {
	sqlStr := "select count(*) from user where username = ?"
	var count int
	err := db.Get(&count, sqlStr, username)
	if err != nil {
		fmt.Printf("get failed, err:%v\n", err)
		return false, err
	}
	return count > 0, nil

}

func QueryUserByUsername() {

}

// InsertUser 向数据库插入新用户
func InsertUser(u *models.User) (err error) {
	// 密码加密
	u.Password = encryptPassword([]byte(u.Password))

	// 执行sql语句
	sqlStr := "INSERT INTO user (user_id, username, password) VALUES (:user_id, :username, :password)"
	_, err = db.NamedExec(sqlStr, u)
	if err != nil {
		return
	}
	return
}

func encryptPassword(data []byte) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum(data))
}

func GetUserByID(id int64) (user *models.User, err error) {
	user = new(models.User)
	sqlStr := `select user_id, username, password from user where user_id = ?`
	err = db.Get(user, sqlStr, id)
	if err != nil {
		if err == sql.ErrNoRows {
			zap.L().Error("不存在此用户！")
			err = ErrInvalidID
		}
		return
	}
	return

}
